import { userService } from './../service/user';
import { redisService } from './../service/redis';
import { V, Connection } from "e:/mjwork/x-engine";
import { X } from "e:/mjwork/xorm";
import { User } from '../model/user';
import { UUID, success, failed, GetCache, SetCache } from '../utils';

export interface SangongUserInRoom{
    roomNumber : number
}

@V.Controller({
    type: Connection.HTTP,
    url: "/room/:method",
    dataType: "json"
})
export class RoomController {
    /**
     * 进入房间
     */
    async join_room(
        token: string,
        room_number: number
    ) {
        if (!room_number || !token) {
            return failed();
        }
        let user = await X.of(User).findOne({
            where: {
                token: token
            }
        });
        if (!user) {
            return failed();
        }

        //三公房间是独立的，理论上可以提供无限个房间
        let info = await redisService.get('room:sangong:' + room_number);
        //如果不存在，那么创建新房间
        if (!info) {
            info = this._genreate_room();
            //上锁
            await redisService.set("room:sangong:" + room_number, info,-1);
        }

        //用户是否可以成为玩家

        //无法成为玩家的情况是否可以成为旁观
        
        return info;

    }

    /**
     * 检索用户在哪个房间中，用于断线重连
     * 
     * @param token 
     * @param gameType 
     */
    async search_in_room(
        token : string,
        gameType : string
    ){
        const user = userService.getUserInfoByToken(token);
        if(!user){
            return failed();
        }
        const roomNo : SangongUserInRoom = await redisService.get("user:room:" + token);
        const roomInfo = await redisService.get("room:" + gameType + ':' + roomNo.roomNumber);
        if(!roomInfo){
            return failed();
        }
        return roomInfo;
    }

    /**
     * 生成默认的房间
     */
    _genreate_room() {
        return { 
            url : '/sangong',
            maxPlayers : 17,
            maxUsers : 100,
        };
    }

}